/*
 * CalculateTime.java Created on Feb 16, 2003 11:05:00 AM
 *
 * Copyright (C) 2003 eRocX Software Group - www.erocx.com
 */
package com.erocx.c24;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

/**
 * <p>Title: CalculateTime</p>
 * <p>Description: calculate the used time</p>
 * 
 * @author		<a href="mailto:eroclu@gmail.com">Andy Lu</a>
 * @version   	1.0
 */

public final class TimeCounter {
    public static final String ORIGINALTIME = "00:00:00";

    private String startTime;
    private String currentTime;

    private int sec, min, hou;

    private long delta;

    private Timer timer;

    public TimeCounter() {
        currentTime = startTime = ORIGINALTIME;
        sec = min = hou = 0;
    }

    private void run() {
        long start = System.currentTimeMillis();
        sec ++;
        if (sec >= 60)  {
            sec = 0;
            min ++;
            if (min >= 60) {
                min = 0;
                hou ++;
            }
        }

        String secStr = String.valueOf(sec);
        String minStr = String.valueOf(min);
        String houStr = String.valueOf(hou);

        if (secStr.length() == 1) {
            secStr = "0" + secStr;
        }
        if (minStr.length() == 1) {
            minStr = "0" + minStr;
        }
        if (houStr.length() == 1) {
            houStr = "0" + houStr;
        }

        currentTime = houStr + ":" + minStr + ":" + secStr;

        delta = System.currentTimeMillis() - start;
    }

    public void start() {
        int delay = 1000;// * (1 - delta); //milliseconds
        ActionListener taskPerformer = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                TimeCounter.this.run();
            }
        };
        timer = new Timer(delay, taskPerformer);
        timer.start();
    }

    public void stop() {
        if (timer != null) {
            timer.stop();
        }
    }

    public void clear() {
        currentTime = startTime = ORIGINALTIME;
        sec = min = hou = 0;
    }

    public String getTime() {
        return currentTime;
    }

    public String getStartTime() {
        return startTime;
    }

}